#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 时间     : 2019-08-03 04:22:23
# 作者     : DL (584054432@qq.com)
# 网址     : https://gitee.com/dingliangPython/
# 软件版本 : Python3.7.3
# 功能     ：

import psutil
import time_ext_
import os
import threading
import sys
import logging
import gc

logger = logging.getLogger("main.check")


def kill_app():
    command='TASKKILL /PID {} /T /F'.format(os.getpid())
    logger.warning("执行：{}".format(command))
    os.system(command)
    os._exit(0)


def warpper_run_time(func):
    def wrapper(self, *args, **kwargs):
        start_time = time_ext_.process_time()
        recult = func(self, *args, **kwargs)
        end_time = time_ext_.process_time()
        execution_time_ = (end_time - start_time)
        logger.debug("方法：{},运行耗时：{}秒".format(func.__name__,execution_time_))
        return recult
    return wrapper


class check_cpu_memory(object):
    """docstring for check_cpu_memory"""

    def __init__(self):
        super(check_cpu_memory, self).__init__()
        self.cpucount = psutil.cpu_count(logical=True)
        # 核心数
        self.process = psutil.Process(os.getpid())
        self.run()
        # 进程

    def reset_app(self):
        python = sys.executable
        os.execl(python, python, * sys.argv)

    def word(self):
        while True:
            cpupercent = self.process.cpu_percent(interval=2)
            # 得到进程CPU占用
            cpu = cpupercent / self.cpucount
            # 内存占用率
            memory = self.process.memory_percent()

            if cpu >= 30 or memory >= 30:
                logger.info("程序运行，CPU占用率：%{}，或内存占用率：%{} 超过30%，10秒后即将重启程序！！！".format(cpu,memory))
                for i in range(10):
                    time_ext_.sleep(1)
                    logger.info("倒计时：{}秒".format(9-i))
                kill_app()
            else:
                logger.info("程序运行，CPU占用率：%{}，或内存占用率：%{} ".format(cpu,memory))

            del cpupercent, cpu, memory
            gc.collect()

            time_ext_.sleep(120)

    def run(self):
        th = threading.Thread(target=self.word)
        th.setDaemon(True)
        th.start()
if __name__ == '__main__':

    check_cpu_memory()
    while 1:
        time_ext_.sleep(5)
